/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package guzik.lukasz.snpmanager.servlets;

import SnpDbEntities.User;
import SnpDbHndInterfaces.DBConnectable;
import com.sun.jndi.url.rmi.rmiURLContext;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.rmi.NotBoundException;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Łukasz 'byku' Guzik
 */
@WebServlet(name = "LoginServlet", urlPatterns =
{
    "/LoginServlet"
})
public class LoginServlet extends HttpServlet
{
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException
    {
	HttpSession httpSession = request.getSession();
	String sessionID = (String) httpSession.getAttribute("db_session");
	DBConnectable connection = (DBConnectable) getServletContext().getAttribute("snpmgr_db_connection");
	String login = (String) request.getParameter("login");
	String pwd = (String) request.getParameter("pwd");

	response.setContentType("text/html;charset=UTF-8");
	PrintWriter out = response.getWriter();
	try
	{
	    out.println("<html>");
	    out.println("<head>");
	    out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
	    out.println("<title>Snippet Manager Web Client</title>");
	    out.println("</head>");

	    if("true".equals(request.getParameter("disconnect")))
	    {
		if(sessionID != null && connection != null)
		{
		    connection.disconnect(sessionID);
		}
		httpSession.removeAttribute("db_session");
		httpSession.removeAttribute("connected_user");
		
		out.println("<body>");
		out.println("<h2>Zostałeś wylogowany!</h2>");

		getServletContext().getRequestDispatcher("/login.jsp").include(request, response);

		out.println("</body>");
		out.println("</html>");
	    } else
	    {
		if(sessionID == null)
		{
		    if(login != null && pwd != null)
		    {
			pwd = User.calculateSHA1(pwd);
			sessionID = connectAndAuth(login, pwd);
		    }
		}

		if(sessionID == null)
		{
		    out.println("<body>");
		    out.println("<h2>Błąd autoryzacji!</h2>");

		    getServletContext().getRequestDispatcher("/login.jsp").include(request, response);

		    out.println("</body>");
		    out.println("</html>");
		} else
		{
		    httpSession.setAttribute("db_session", sessionID);
		    if(httpSession.getAttribute("connected_user") == null)
		    {
			connection = (DBConnectable) getServletContext().getAttribute("snpmgr_db_connection");
			httpSession.setAttribute("connected_user", connection.getUserHandler(sessionID).getUser(login));
		    
		    }
		    getServletContext().getRequestDispatcher("/MainServlet").forward(request, response);
		}
	    }
	} catch(Exception e)
	{
	    e.printStackTrace(out);
	} finally
	{
	    out.close();
	}
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException
    {
	processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException
    {
	processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo()
    {
	return "Short description";
    }// </editor-fold>

    private String connectAndAuth(String login, String pwd) throws IOException,
	    NotBoundException
    {
	DBConnectable connection = (DBConnectable) getServletContext().getAttribute("snpmgr_db_connection");
	String sessionID;

	if(connection == null)
	{
	    Properties props = new Properties();
	    props.load(new FileInputStream(getServletContext().getRealPath("connection.properties")));
	    String server = props.getProperty("server.address");
	    connection = (DBConnectable) java.rmi.Naming.lookup(server);
	    getServletContext().setAttribute("snpmgr_db_connection", connection);
	}

	sessionID = connection.connectAndAuth(login, pwd);

	return sessionID;
    }
}
